import { spawn } from "child_process";

export function pythonname(): Promise<string> {
    return new Promise((res, rej) => {
        const ls = spawn('python', ['-V']);
        ls.stdout.on('data', (data: string) => {
            data = data.toString()
            if (data.slice(0, 8) === 'Python 3') {
                res('python')
            } else {
                const l = spawn('python3', ['-V'])
                l.stdout.on('data', (data: string) => {
                    data = data.toString()
                    if (data.slice(0, 8) === 'Python 3') {
                        res('python3')
                    } else {
                        rej(false)
                    }
                })
            }
        });

        ls.on('error', (_code) => {
            const l = spawn('python3', ['-V'])
            l.stdout.on('data', (data: string) => {
                data = data.toString()
                if (data.slice(0, 8) === 'Python 3') {
                    res('python3')
                } else {
                    rej(false)
                }
            })
        })

        ls.stderr.on('data', (data) => {
            data = data.toString()
            if (data.slice(0, 8) === 'Python 3') {
                res('python')
            } else {
                const l = spawn('python3', ['-V'])
                l.stdout.on('data', (data: string | Buffer) => {
                    data = data.toString()
                    if (data)
                        if (data.slice(0, 8) === 'Python 3') {
                            res('python3')
                        } else {
                            rej(false)
                        }
                })
            }
        });
    })
}
